package com.he.handler;

import com.he.utils.AppUtil;
import io.netty.channel.*;
import io.netty.handler.codec.http.*;
import io.netty.handler.stream.ChunkedFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.activation.MimetypesFileTypeMap;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.RandomAccessFile;
import java.net.URLDecoder;


/**
 * @author HEHUIJUN
 */
@SuppressWarnings("all")
public class SimpleHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

    private static Logger logger= LoggerFactory.getLogger(SimpleHandler.class);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
        String uri= URLDecoder.decode(request.uri(),"utf-8").replace('/', File.separatorChar).replace('\\',File.separatorChar);
        //1.判断请求是否符合条件|请求方式|解码|路径|本地文件是否存在等等
        boolean isAccess=AppUtil.isAccess(ctx,request,uri);
        logger.debug("是否可以访问："+isAccess);
        if(!isAccess)return;

        File file=new File(AppUtil.convertUrlToLocalPath(request,uri));
        if(file.isDirectory()){
            if(uri.endsWith("/")){
                AppUtil.sendListing(ctx,file);
            }else {
                AppUtil.sendRedirect(ctx,uri+"/");
            }

        }else {
            AppUtil.writeToUser(ctx,request,file);
        }

    }

}
